'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: provider_entity.py
* @Time: 2025/9/22
* @All Rights Reserve By Brtc
'''
import os.path
from typing import Any

import yaml
from pydantic import BaseModel, Field

from internal.lib.helper import dynamic_import
from .tool_entity import ToolEntity


class ProviderEntity(BaseModel):
    """服务商提供实体类， 映射的是数据provider.yaml 文件"""
    name:str # 名字
    label:str # 标签
    description:str # 描述
    icon:str# 图标
    background:str # 背景色
    category:str # 分类信息
    create_at: int=0 # 创建时间

class Provider(BaseModel):
    """服务提供商,可以获取所有该服务提供商提供的所有工具， 包含工具的描述、图标、等多个信息"""
    name:str # 服务商名字
    position:int # 服务商前端的位置信息
    provider_entity:ProviderEntity # 服务商实体类
    tool_entity_map:dict[str, ToolEntity] = Field(default_factory = dict)
    tool_func_map:dict[str, Any] = Field(default_factory = dict)

    def _provider_init(self):
        """服务商初始化函数"""
        # 1、获取当前类的路径，并计算服务提供商的地址&路径
        current_path = os.path.abspath(__file__)
        entities_path = os.path.dirname(current_path)
        provider_path = os.path.join(os.path.dirname(entities_path),"providers", self.name)

        # 2、组装获取position.yaml 数据
        position_yaml_path = os.path.join(provider_path, "position.yaml")
        with open(position_yaml_path, encoding="utf-8") as f:
            position_yaml_data = yaml.safe_load(f)

        #3、循环获取工具名称
        for tool_name in position_yaml_data:
            # 4、获取工具的yaml 数据
            tool_yaml_path = os.path.join(provider_path, f"{tool_name}.yaml")
            with open(tool_yaml_path, encoding="utf-8") as f:
                tool_yaml_data = yaml.safe_load(f)

            # 5、将工具信息填充到  tool_enenties_map 中
            self.tool_entity_map[tool_name] = ToolEntity(**tool_yaml_data)

            # 6、动态导入对应的工具并填充到tool_func_map中
            self.tool_func_map[tool_name] = dynamic_import(
                f"internal.core.tools.builtin_tools.providers.{self.name}", tool_name
            )


    def __init__(self, **kwargs):
        """构造函数"""
        super().__init__(**kwargs)
        self._provider_init()

    def get_tool(self, tool_name:str)->Any:
        """根据工具名字,来获取工具函数"""
        return self.tool_func_map.get(tool_name)

    def get_tool_entity(self, tool_name:str):
        """根据工具名字,来获取工具实体"""
        return self.tool_entity_map.get(tool_name)

    def get_tool_entities(self):
        """获取服务商所有的工具名称"""
        return self.tool_entity_map.values()
